package yunwo.cn.yzstation.view.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.zhy.autolayout.AutoLinearLayout;

import java.text.SimpleDateFormat;
import java.util.Date;

import yunwo.cn.yzstation.R;
import yunwo.cn.yzstation.base.MyBaseActivity;
import yunwo.cn.yzstation.base.Yzapp;
import yunwo.cn.yzstation.bean.OrderDetailsBean;
import yunwo.cn.yzstation.bean.printBean.PrintLabelBean;
import yunwo.cn.yzstation.bean.printBean.PrintTicketBean;
import yunwo.cn.yzstation.config.GoodsSP;
import yunwo.cn.yzstation.presenter.OrderDetailsPersenter;
import yunwo.cn.yzstation.api.OrderDetailsView;
import yunwo.cn.yzstation.printer.YHBPrintService;
import yunwo.cn.yzstation.utils.StringUtil;

/**
 * Created by lao on 2017/9/9.
 */

public class OrderDetailsActivity extends MyBaseActivity implements View.OnClickListener, OrderDetailsView {

    private ImageView mEnsconce1;
    private ImageView mEnsconce2;
    private LinearLayout mFeeinfo;
    private LinearLayout mOrderinfo;
    boolean isopen = false;
    boolean isopenFee = false;
    private String mTrackingId;
    private OrderDetailsPersenter mOrderDetailsPersenter;


    private TextView mEndOrganName;
    private TextView mTrackingNumber;
    private TextView mCreateDate;
//    private TextView mBelongOrganName;
    private TextView mConsignorAddress;
    private TextView mConsignor;
    private TextView mConsignorPhone;
    private TextView mConsigneeAddress;
    private TextView mConsigneeName;
    private TextView mConsigneePhone;
    private TextView mPayment;
    private TextView mDelivery;
    private TextView mProductName;
    private TextView mWeight;
    private TextView mPackName;
    private TextView mVolume;
    private TextView mTotalFee;
    private TextView mFreight;
    private TextView mAdvanceTransferCharges;
    private TextView mReputation;
    private TextView mServiceCharges;
    private TextView mPremium;
    private TextView mSonghuo;
    private TextView mFloorCharges;
    private TextView mOtherCharges;
    private TextView mBaozhuangfei;
    private TextView mCollectMoney;
    private TextView mRebate;
    private TextView mTotalFee1;
    private TextView mAgainpritnf;

    private AutoLinearLayout mSelfLL;
    private TextView mSelfTV;
    private TextView mSelfInfoTV;
    private AutoLinearLayout mSendGoodsLL;
    private TextView mSendGoodsTV;
    private TextView mSendGoodsInfoTV;
    private EditText mTipTagET;
    private EditText mTipTagNumET;
    private EditText mTicket;
    private TextView mAgainpritnf1;
    private TextView mCancel;
    public boolean printWaybillType = false;
    public boolean printLabelType = false;
    private AlertDialog mAlertDialog;
    private TextView mCancell;
    private SharedPreferences addressShare;
    private SharedPreferences.Editor addresseditor;
    OrderDetailsBean.DataBean dataBean;
    private TextView mNumber;
    private String mAddress;
    private String mAddress1;
    private String mPrintername;
    private TextView mBaoguanfee;
    private TextView mShangloufee;
    private TextView mState;
    private SharedPreferences mPrinterShare;
    private SharedPreferences.Editor mPrinteredit;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addressShare = getSharedPreferences("information_addresspiant", Context.MODE_PRIVATE);
        addresseditor = addressShare.edit();
        mPrinterShare = getSharedPreferences("printerstate", Context.MODE_PRIVATE);
        mPrinteredit = mPrinterShare.edit();
        mTrackingId = getIntent().getExtras().getString("trackingId", "");
        mOrderDetailsPersenter = new OrderDetailsPersenter(this, this);
        mOrderDetailsPersenter.getDetailsData(mTrackingId);
        mAddress = addressShare.getString("address", "");
        mAddress1 = addressShare.getString("address1", "");
        mPrintername = addressShare.getString("printername", "XT4131");
        initView();

    }

    private void initView() {
        mState = (TextView) findViewById(R.id.state);
        mBaoguanfee = (TextView) findViewById(R.id.baoguanfee);
        mShangloufee = (TextView) findViewById(R.id.shangloufee);
        mNumber = (TextView) findViewById(R.id.number);
        mEndOrganName = (TextView) findViewById(R.id.endOrganName);
        mTrackingNumber = (TextView) findViewById(R.id.trackingNumber);
        mCreateDate = (TextView) findViewById(R.id.createDate);
//        mBelongOrganName = (TextView) findViewById(R.id.belongOrganName);
        mConsignorAddress = (TextView) findViewById(R.id.consignorAddress);
        mConsignor = (TextView) findViewById(R.id.consignor);
        mConsignorPhone = (TextView) findViewById(R.id.consignorPhone);
        mConsigneeAddress = (TextView) findViewById(R.id.consigneeAddress);
        mConsigneeName = (TextView) findViewById(R.id.consigneeName);
        mConsigneePhone = (TextView) findViewById(R.id.consigneePhone);
        mPayment = (TextView) findViewById(R.id.payment);
        mDelivery = (TextView) findViewById(R.id.delivery);
        mProductName = (TextView) findViewById(R.id.productName);
        mWeight = (TextView) findViewById(R.id.weight);
        mPackName = (TextView) findViewById(R.id.packName);
        mVolume = (TextView) findViewById(R.id.volume);
        mTotalFee = (TextView) findViewById(R.id.totalFee);
        mFreight = (TextView) findViewById(R.id.freight);
        mAdvanceTransferCharges = (TextView) findViewById(R.id.advanceTransferCharges);
        mReputation = (TextView) findViewById(R.id.reputation);
        mServiceCharges = (TextView) findViewById(R.id.serviceCharges);
        mPremium = (TextView) findViewById(R.id.premium);
        mSonghuo = (TextView) findViewById(R.id.tihuo);
        mFloorCharges = (TextView) findViewById(R.id.floorCharges);
        mOtherCharges = (TextView) findViewById(R.id.otherCharges);
        mBaozhuangfei = (TextView) findViewById(R.id.baozhuangfei);
        mCollectMoney = (TextView) findViewById(R.id.collectMoney);
        mRebate = (TextView) findViewById(R.id.rebate);
        mTotalFee1 = (TextView) findViewById(R.id.totalFee1);
        mAgainpritnf = (TextView) findViewById(R.id.againpritnf);

        mEnsconce1 = (ImageView) findViewById(R.id.ensconce1);
        mEnsconce2 = (ImageView) findViewById(R.id.ensconce2);
        mOrderinfo = (LinearLayout) findViewById(R.id.orderinfo);
        mFeeinfo = (LinearLayout) findViewById(R.id.feeinfo);
        mEnsconce1.setOnClickListener(this);
        mEnsconce2.setOnClickListener(this);
        mAgainpritnf.setOnClickListener(this);

    }

    @Override
    protected String settiltile() {
        return "订单详情";
    }

    @Override
    protected int getLayoutRsid() {
        return R.layout.activity_orderactivity;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.againpritnf:
                initPrintf();
                break;
            case R.id.ensconce1:
                isopen = !isopen;
                if (isopen) {
                    mOrderinfo.setVisibility(View.GONE);
                } else {

                    mOrderinfo.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.ensconce2:
                isopenFee = !isopenFee;
                if (isopenFee) {
                    mFeeinfo.setVisibility(View.GONE);
                } else {
                    mFeeinfo.setVisibility(View.VISIBLE);
                }
                break;
        }
    }

    private void initPrintf() {
         printWaybillType = false;
         printLabelType = false;
        final AlertDialog.Builder builder = new AlertDialog.Builder(OrderDetailsActivity.this);
        View rootView = LayoutInflater.from(OrderDetailsActivity.this).inflate(R.layout.printfagin, null);

        mCancell = (TextView) rootView.findViewById(R.id.cancell);
        mTicket = (EditText) rootView.findViewById(R.id.ticket);
        mSelfTV = (TextView) rootView.findViewById(R.id.selfTV);
        mTipTagET = (EditText) rootView.findViewById(R.id.tipTagET);
        mTipTagET.setSelection(mTipTagET.length());
        mSelfLL = (AutoLinearLayout) rootView.findViewById(R.id.selfLL);
        mSendGoodsLL = (AutoLinearLayout) rootView.findViewById(R.id.sendGoodsLL);
        mSelfInfoTV = (TextView) rootView.findViewById(R.id.selfInfoTV);
        mSendGoodsTV = (TextView) rootView.findViewById(R.id.sendGoodsTV);
        mTipTagNumET = (EditText) rootView.findViewById(R.id.tipTagNumET);
        mTipTagNumET.setEnabled(false);
        mAgainpritnf1 = (TextView) rootView.findViewById(R.id.againpritnf);
        mSendGoodsInfoTV = (TextView) rootView.findViewById(R.id.sendGoodsInfoTV);
        setWatcherListener(OrderDetailsActivity.this,mTipTagET);
        if (dataBean != null) {
            mTipTagNumET.setText(dataBean.getGoodsNumber()+"");
        }

        initprintfevent();
        builder.setView(rootView);
        builder.setCancelable(false);
        mAlertDialog = builder.create();
        mAlertDialog.show();

    }

    private void initprintfevent() {
        mAgainpritnf1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean printstate = mPrinterShare.getBoolean("state", false);
                if (!printstate) {
                    printf();
                }else {
                    Toast.makeText(OrderDetailsActivity.this, "请等待打印完成", Toast.LENGTH_SHORT).show();
                    return;
                }
                mAlertDialog.dismiss();
            }
        });

        mCancell.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mAlertDialog.dismiss();
            }
        });

        mSelfLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (printWaybillType) {   //printWaybillType
                    printWaybillType = false;
                    mSelfTV.setBackgroundResource(R.drawable.click_icon);
                } else {
                    printWaybillType = true;
                    mSelfTV.setBackgroundResource(R.drawable.checkbox_selector);
                }


            }
        });
        mSendGoodsLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {    //printLabelType
                if (printLabelType) {
                    printLabelType = false;
                    mSendGoodsTV.setBackgroundResource(R.drawable.click_icon);
                } else {
                    printLabelType = true;
                    mSendGoodsTV.setBackgroundResource(R.drawable.checkbox_selector);
                }

            }
        });
    }

    private void printf() {




        Intent intent = new Intent(OrderDetailsActivity.this,YHBPrintService.class);
        Bundle bundle = new Bundle();
        bundle.putString("printername", mPrintername);

        if (!printWaybillType) { //标签
            bundle.putString(YHBPrintService.Start_address_ticket, mAddress1);

        }else {
            bundle.putString(YHBPrintService.Start_address_ticket,"");

        }


        if (!printLabelType) {   //运单
            intent.putExtra(YHBPrintService.Start_address_label, mAddress);

        }else {
            intent.putExtra(YHBPrintService.Start_address_label,"");

        }



        final PrintLabelBean labelBean = new PrintLabelBean();
        labelBean.setGroupName("云企集团");
        labelBean.setGnd(dataBean.getGnd());
        labelBean.setCompanyName(Yzapp.getInstance().getgetBeginOrgName());
//        labelBean.setTrackNumber(waybillNumber);
        labelBean.setTrackNumber(dataBean.getTrackingNumber());
        labelBean.setStartCity(Yzapp.getInstance().getgetBeginOrgName());
//        labelBean.setEndCity(goodsShare.getString("desCityName", ""));
        labelBean.setEndCity(dataBean.getEndOrganName());   //到站城市
//        districtName
        labelBean.setTransStation(dataBean.getTransferOrganName());
        labelBean.setSendMethod(dataBean.getDeliveryName());
//        labelBean.setNumber(String.valueOf(dataBean.getGoodsNumber()));
        labelBean.setNumber(dataBean.getGoodsNumber()+"");
        //mTipTagNumET

        String trim = mTipTagET.getText().toString().trim();
        Log.d("vvvvvxxxxx", "打印标签" + trim);
        labelBean.setPosition(mTipTagET.getText().toString().trim());
        labelBean.setProductName(dataBean.getProductName());
        labelBean.setUserName(dataBean.getConsigneeName());
        labelBean.setSendPersonName(dataBean.getCreateUserName());
        labelBean.setTime(dataBean.getCreateDate());
        bundle.putSerializable(YHBPrintService.Start_bean_label,labelBean);
//        intent.getExtras().putSerializable(YHBPrintService.Start_bean_label,labelBean);

        final PrintTicketBean ticketBean = new PrintTicketBean();
        ticketBean.setShangloufee(dataBean.getUpstairsCharges()+"");
        ticketBean.setServiceFee(dataBean.getServiceCharges()+"");
        ticketBean.setVolume(dataBean.getVolume()+"");


        ticketBean.setWeight(dataBean.getWeight()+"");
        ticketBean.setPackageName(dataBean.getPackName());
        ticketBean.setShengjiaFee(dataBean.getReputation()+"");
        ticketBean.setLandFee(dataBean.getFloorCharges()+"");  //落地费
        ticketBean.setDeliveryFee(dataBean.getDeliveryCharges()+"");//送货费
        ticketBean.setZhuangxieFee("");  //装卸费
        ticketBean.setTransFee(dataBean.getAdvanceTransferCharges()+"");  // 中转费
        ticketBean.setOtherFee(dataBean.getOtherCharges()+"");  //其他费
        ticketBean.setDaidianFee("");   //代垫贷款
        ticketBean.setDaikuanFee(dataBean.getProcurationCharges()+""); //贷款
        ticketBean.setDaishouFee(dataBean.getCollectMoney()+""); //代收贷款
        ticketBean.setBaoguanFee(dataBean.getCustomsCharges()+""); //报关
        ticketBean.setTime(dataBean.getCreateDate());

        boolean b = dataBean.getReceiptPay().equals("是") ? true : false;
        ticketBean.setHuidan(b);
        ticketBean.setTicket(mTicket.getText().toString());
        ticketBean.setGroupName("云企集团");
        ticketBean.setCompanyName(Yzapp.getInstance().getgetBeginOrgName());
        ticketBean.setTrackNumber(dataBean.getTrackingNumber());
        ticketBean.setStartCity(Yzapp.getInstance().getgetBeginOrgName());

        ticketBean.setEndCity(dataBean.getEndOrganName());    //到站城市
        ticketBean.setTransStation(dataBean.getTransferOrganName());
        ticketBean.setServiceMethod(dataBean.getDeliveryName());


        ticketBean.setNumber(dataBean.getGoodsNumber()+"");
        ticketBean.setProductName(dataBean.getProductName());

        ticketBean.setSendPersonPhone(dataBean.getConsignorPhone());  //发货人电话号码
        ticketBean.setSendPersonName(dataBean.getConsignorName());
        ticketBean.setSendPersonAddress(dataBean.getConsignorAddress());
        ticketBean.setUserName(dataBean.getConsigneeName());
        ticketBean.setUserAddress(dataBean.getConsigneeAddress());
        ticketBean.setUserPhone(dataBean.getConsigneePhone());
        ticketBean.setFreight(dataBean.getFreight()+"");
        ticketBean.setTotalFee(dataBean.getTotalFee()+"");
        ticketBean.setRemarks(dataBean.getRemarks());
        ticketBean.setPayment(dataBean.getPayMeansName());
        ticketBean.setBaofeiFee(dataBean.getPremium()+"");
        bundle.putSerializable(YHBPrintService.Start_bean_ticket,ticketBean);
//        intent.getExtras().putSerializable(YHBPrintService.Start_bean_ticket,ticketBean);
        intent.putExtras(bundle);
        startService(intent);
//        sendPrintStatus(intent);



    }

    @Override
    public void getOrderDetailsSuccess(OrderDetailsBean.DataBean dataBean) {
        this.dataBean = dataBean;
        setData(dataBean);
        String endOrganName = dataBean.getEndOrganName();
        Log.d("bbbbbbbbb", endOrganName);
    }

    private void setData(OrderDetailsBean.DataBean dataBean) {
//
        switch (dataBean.getTrackingStatus()) {
            case 1:
                mState.setText("派单中");
                mState.setVisibility(View.VISIBLE);
                mState.setBackgroundResource(R.drawable.list_icon_end);
                break;
            case 2:
                mState.setText("待提货");
                mState.setVisibility(View.VISIBLE);
                mState.setBackgroundResource(R.drawable.list_icon_end);
                break;
            case 3:
                mState.setText("拉包中");
                mState.setVisibility(View.VISIBLE);
                mState.setBackgroundResource(R.drawable.list_icon_end);
                break;
            case 4:
                mState.setText("待发车");
                mState.setVisibility(View.VISIBLE);
                mState.setBackgroundResource(R.drawable.list_icon_end);
                break;
            case 5:
                mState.setText("运输中");
                mState.setVisibility(View.VISIBLE);
                mState.setBackgroundResource(R.drawable.list_icon_end);
                break;
            case 6:
                mState.setText("待配送");
                mState.setVisibility(View.VISIBLE);
                mState.setBackgroundResource(R.drawable.list_icon_end);
                break;
            case 7:
                mState.setText("待签收");
                mState.setVisibility(View.VISIBLE);
                mState.setBackgroundResource(R.drawable.list_icon_end);
                break;
            case 8:
                mState.setText("已签收");
                mState.setVisibility(View.VISIBLE);
                mState.setBackgroundResource(R.drawable.icon_have_in_hand);
                break;
            case 9:
                mState.setText("已取消");
                mState.setVisibility(View.VISIBLE);
                mState.setBackgroundResource(R.drawable.list_icon_end);
                break;

        }
        mShangloufee.setText(conversion(dataBean.getUpstairsCharges()+""));
        mBaoguanfee.setText(conversion(dataBean.getCustomsCharges()+""));
        mNumber.setText(dataBean.getGoodsNumber()+"");
        mEndOrganName.setText(dataBean.getEndOrganName());
        mTrackingNumber.setText(dataBean.getTrackingNumber());
        mCreateDate.setText("下单时间：  "+dataBean.getCreateDate());
//        mBelongOrganName.setText(dataBean.getBelongOrganName());
        mConsignorAddress.setText(dataBean.getConsignorAddress());
        mConsignor.setText(dataBean.getConsignorName());
        mConsignorPhone.setText(dataBean.getConsignorPhone());
        mConsigneeAddress.setText(dataBean.getConsigneeAddress());
        mConsigneeName.setText(dataBean.getConsigneeName());
        mConsigneePhone.setText(dataBean.getConsigneePhone());
        mPayment.setText(dataBean.getPayMeansName());
        mDelivery.setText(dataBean.getDeliveryName());
        mProductName.setText(dataBean.getProductName());
        mWeight.setText(dataBean.getWeight() + "");
        mPackName.setText(dataBean.getPackName());
        mVolume.setText(dataBean.getVolume() + "");
        mTotalFee.setText(conversion(dataBean.getTotalFee() + ""));
        mFreight.setText(conversion(dataBean.getFreight() + ""));
        mAdvanceTransferCharges.setText(conversion(dataBean.getAdvanceTransferCharges() + ""));
        mReputation.setText(conversion(dataBean.getReputation() + ""));
        mServiceCharges.setText(conversion(dataBean.getServiceCharges() + ""));
        mPremium.setText(conversion(dataBean.getPremium() + ""));

        mSonghuo.setText(conversion(dataBean.getDeliveryCharges()+""));

        mFloorCharges.setText(conversion(dataBean.getFloorCharges() + ""));
        mOtherCharges.setText(conversion(dataBean.getOtherCharges() + ""));
        mCollectMoney.setText(conversion(dataBean.getCollectMoney() + ""));
        mRebate.setText(conversion(dataBean.getRebate() + ""));
        mTotalFee1.setText(conversion(dataBean.getTotalFee() + ""));
        Double collectMoney = dataBean.getCollectMoney();
        Log.d("dddddddddd", String.valueOf(collectMoney));
    }


    public String conversion(String value) {
        if (value == null || value.equals("0")) {
            return "0.00元";
        } else {
            return value + "元";
        }
    }
    public String getTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd hh:mm");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);

        return str;
    }

    private void setWatcherListener(final Activity activity, final EditText editText) {
        TextWatcher watchContent = new TextWatcher() {


            private boolean isChanged = false;
            private CharSequence temp;

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                switch (editText.getId()) {
                    case R.id.tipTagET:
                        try {
                            int tipTag = Integer.parseInt(mTipTagET.getText().toString().trim());
                            int Number = Integer.parseInt(mNumber.getText().toString().trim());
                            if (tipTag > Number) {
                                Toast.makeText(OrderDetailsActivity.this, "标签号不能大于总件数", Toast.LENGTH_SHORT).show();
                                mTipTagET.setText("1");
                                mTipTagET.setSelection(mTipTagET.length());
                            } else {

                        /*if (tipTag == 1) {
                            tipTag = 0;
                        }*/
                                if (tipTag == Number) {
                                    mTipTagNumET.setText(1 + "");
                                    mTipTagET.setSelection(mTipTagET.length());
                                    return;
                                }

                                int i = Number - (tipTag - 1);
                                mTipTagNumET.setText(i + "");
                                mTipTagET.setSelection(mTipTagET.length());
                            }
                        } catch (Exception e) {
                        }

                        break;
                }

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        };
        editText.addTextChangedListener(watchContent);
    }
}
